package com.leeson.portal.core.service.h3c;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;

import com.leeson.portal.core.model.Config;
import com.leeson.portal.core.service.utils.PortalUtil;

public class PacketSendReceiveTest{
	
	private static Logger log = Logger.getLogger(PacketSendReceiveTest.class);

	private static Config config = Config.getInstance();
	/**
	 * basIp AC通信IP地址 basPort AC socket端口号 sharedSecret BAS和Portal
	 * Server之间的共享密钥secret 相当于签名 authType 定义认证方式 有PAP/CHAP两种 timeoutSec 定义请求超时时间
	 * 单位秒 portalVer portal协议版本 目前有1.0和2.0
	 */
	final static String basIp = config.getBas_ip();
	final static String bas = config.getBas();
	final static int basPort = Integer.parseInt(config.getBas_port());
	final static String sharedSecret = config.getSharedSecret();
	final static String authType = config.getAuthType();
	final static int timeoutSec = Integer.parseInt(config.getTimeoutSec());
	final static int portalVer = Integer.parseInt(config.getPortalVer());
	
	
	public static byte[] reqInfo(short SerialNo, String UserIP) {
		PacketBuilder localPacketBuilder = new PacketBuilder();
	    localPacketBuilder.setHead((byte)80, (byte)portalVer); //headVer
	    localPacketBuilder.setHead((byte)81, (byte)9); //headType
	    localPacketBuilder.setHead((byte)87, CommonFunctions.ipv4ToBytes(UserIP)); //headUserIPv4
	    localPacketBuilder.setHead((byte)84, (short)SerialNo);  //headSerialNo
	    localPacketBuilder.setAttribute((byte)8, new byte[2]);  //08040000
	    localPacketBuilder.setShareSecret(sharedSecret.getBytes());
	    try
	    {
	      localPacketBuilder.setDestineAddress(InetAddress.getByName(basIp)); //设置目的IP
	      localPacketBuilder.setDestinePort(basPort);  //设置目的端口
	    }
	    catch (UnknownHostException localUnknownHostException)
	    {
	      localUnknownHostException.printStackTrace();
	    }
	    DatagramSocket dataSocket = null;// 创建连接
	    try {
			dataSocket = new DatagramSocket();
			dataSocket.send(localPacketBuilder.composeWebPacket());
			byte[] ACK_Data_Temp = new byte[100];// 接收服务器的数据包
			DatagramPacket receivePacket = new DatagramPacket(
					ACK_Data_Temp, 100);
			dataSocket.setSoTimeout(timeoutSec * 1000);// 设置请求超时3秒
			dataSocket.receive(receivePacket);
			byte[] ACK_Data = new byte[receivePacket.getLength()]; // 构建接收包
			for (int i = 0; i < ACK_Data.length; i++) {
				ACK_Data[i] = receivePacket.getData()[i];
			}
			if(config.getDebug().equals("1")){
				log.info("ACK"
						+ PortalUtil.Getbyte2HexString(ACK_Data));
			}
			
			return ACK_Data;
		} catch (IOException e) {
			if(config.getDebug().equals("1")){
				log.info("建立INFO会话，请求无响应!!!");
			}
			byte[] ErrorInfo = new byte[1];// 创建ErrorInfo包
			ErrorInfo[0] = (byte) 01;
			return ErrorInfo;
		}finally {
			dataSocket.close();
		}
		
		
	}
}